import os
import uuid
from fastapi import UploadFile, HTTPException
from pathlib import Path
from typing import Optional

# 配置文件存储路径
ICON_STORAGE_PATH = "static/icons/uploads"
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "webp", "svg"}
MAX_FILE_SIZE = 2 * 1024 * 1024  # 2MB

class FileService:
    @staticmethod
    async def save_icon(file: UploadFile, user_id: str) -> dict:
        """保存用户上传的图标，返回文件访问路径"""
        # 1. 校验文件格式
        FileService._validate_file(file)
        
        # 2. 生成唯一文件名（避免冲突）
        file_ext = file.filename.split(".")[-1]
        new_filename = f"{user_id}_{uuid.uuid4()}.{file_ext}"
        save_path = Path(ICON_STORAGE_PATH) / new_filename

        # 3. 确保目录存在
        os.makedirs(ICON_STORAGE_PATH, exist_ok=True)

        # 4. 保存文件
        try:
            with open(save_path, "wb") as buffer:
                buffer.write(await file.read())
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}")

        # 5. 返回访问路径（如 /static/icons/filename.png）
        return {
            "file_name": new_filename,
            "file_url": f"/static/icons/uploads/{new_filename}",
            "file_size": file.size,
            "file_type": file_ext,
        }

    @staticmethod
    async def delete_icon(file_url: str) -> bool:
        """删除指定路径的图标文件"""
        file_path = Path(file_url.lstrip("/"))  # 去掉前面的斜杠
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件不存在")
        try:
            os.remove(file_path)
            return True
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"文件删除失败: {str(e)}")
    
    @staticmethod
    def _validate_file(file: UploadFile):
        """校验文件大小和格式"""
        # 检查文件大小
        if file.size > MAX_FILE_SIZE:
            raise HTTPException(status_code=413, detail="文件大小超过 2MB 限制")

        # 检查文件扩展名
        file_ext = file.filename.split(".")[-1].lower()
        if file_ext not in ALLOWED_EXTENSIONS:
            raise HTTPException(
                status_code=400,
                detail=f"不支持的文件格式，允许的格式: {', '.join(ALLOWED_EXTENSIONS)}"
            )